package com.rayson.oneapi.interceptors;

import com.alibaba.fastjson.JSON;
import com.rayson.oneapi.common.R;
import com.rayson.oneapi.constant.UserConstant;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Author: rayson
 * Description: 此拦截器为了校验用户是否登录？未登录直接返回401
 * Version: 1.0
 * Date: 2024-09-04 20:20
 */
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (user == null) {
            response.setStatus(401);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSON.toJSONString(R.error("未登录")));
            return false;
        }
        return true;
    }
}
